//
//  LocationManager.m
//  PersonalProject
//
//  Created by 卫建 on 15/12/18.
//  Copyright © 2015年 卫建. All rights reserved.
//

#import "LocationManager.h"
#import <CoreLocation/CoreLocation.h>

@interface LocationManager ()<CLLocationManagerDelegate>



@end

static LocationManager *manager = nil;
@implementation LocationManager

+(instancetype)sharedLocationManager
{
    return [[self alloc]init];
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil)
        {
            manager = [super allocWithZone:zone];
        }
    });
    
    return manager;
}

#pragma mark-------开始定位
-(void)startLocation
{
    if (self.locationManager == nil)
    {
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        
//#warning 这里有一个可选,一会试一试
        //请求用户允许使用定位
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    //判断定位服务是否可用,并且用户是否允许定位
    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied)
    {
        //开启定位服务
        [self.locationManager startUpdatingLocation];
    }
    
    //设置定位的精度
    CLLocationDistance distance = 10;
    
    self.locationManager.distanceFilter = distance;
    
//#warning 定位的耗电问题需待解决
    //定位的质量,定位很耗电,质量选择越高定位越耗电
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    
}


//-(void)stopLocation
//{
//    [self.locationManager stopUpdatingLocation];
//}

//#pragma mark-----更新位置信息的方法
//- (void)handleTime
//{
//    [_locationManager startUpdatingLocation];
//}

#pragma mark--------更新位置信息的方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0)
{
    NSLog(@"位置定位信息");
    
    //在单例中进行block调用
    CLLocation *location = locations.firstObject;
    
    if (self.updateBlock)
    {
        CLLocationCoordinate2D coordinate = location.coordinate;
        
        coordinate = [self getMarsCoorWithEarthCoor:coordinate];
        
        self.updateBlock(coordinate);
    
    }
    
    
//    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
//    CLLocation *currentLocation = [locations lastObject];
//    
//    CLLocationCoordinate2D coor = currentLocation.coordinate;
//    self.latitude =  coor.latitude;
//    self.longitude = coor.longitude;
    

}



#pragma mark-------定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位失败");
}

#pragma mark -火星坐标

const double pi = 3.14159265358979324;
const double a = 6378245.0;
const double ee = 0.00669342162296594323;


//将CLLocation定位的coordinate传进来，就可以计算出用于在高德地图中使用的火星坐标了
-(CLLocationCoordinate2D)getMarsCoorWithEarthCoor:(CLLocationCoordinate2D)earthCoor
{
    CLLocationCoordinate2D marsCoor;
    if (outOfChina(earthCoor.latitude, earthCoor.longitude)) {
        marsCoor = earthCoor;
        return marsCoor;
    }
    double dLat = transformLat(earthCoor.longitude-105.0, earthCoor.latitude-35.0);
    double dLon = transformLon(earthCoor.longitude-105.0, earthCoor.latitude-35.0);
    double radLat = earthCoor.latitude/180.0*pi;
    double magic = sin(radLat);
    magic = 1-ee*magic*magic;
    double sqrtMagic = sqrt(magic);
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
    dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi);
    marsCoor = CLLocationCoordinate2DMake(earthCoor.latitude+dLat, earthCoor.longitude+dLon);
    return marsCoor;
}

static bool outOfChina(double lat, double lon)
{
    if (lon < 72.004 || lon > 137.8347)
        return true;
    if (lat < 0.8293 || lat > 55.8271)
        return true;
    return false;
}

static double transformLat(double x, double y)
{
    double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x));
    ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
    ret += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0;
    ret += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0;
    return ret;
}

static double transformLon(double x, double y)
{
    double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x));
    ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0;
    ret += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0;
    ret += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0;
    return ret;
}
-(BOOL)ismainStringContainSubString:(NSString *)mainString  subString:(NSString *)subString
{
    
    NSRange range=[mainString rangeOfString:subString];
    if(range.location!=NSNotFound){
        return true;
    }else{
        return false;
    }
}


//#pragma mark-------地理编码,根据地址获取经纬度
//-(void)getCoordinateWithAddress:(NSString *)address
//                     withFinish:(GeographyCodingBlock)finishBlock
//{
//    //地理编码和逆地理编码都需要通过iOS提供一个编码类
//    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
//    [geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//       
//        dispatch_async(dispatch_get_main_queue(), ^{
//           
//            CLPlacemark *placeMark = placemarks.firstObject;
//            
//            finishBlock(placeMark.location.coordinate);//该回调的东西
//            
//        });
//        
//    }];
//}
//
#pragma mark-------逆地理编码
-(void)getAddressWithCoordinate:(CLLocationCoordinate2D)coordinate
                     withFinish:(UpGeographyCodingBlock)finishBlock
{
    self.geocoder = [[CLGeocoder alloc]init];
    
    self.location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    NSLog(@"----------------#######---------%@",self.location);
    
    [_geocoder reverseGeocodeLocation:self.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            //拿出找到的第一个元素
            self.mark = placemarks.firstObject;
            
            NSLog(@"详细信息:%@",self.mark.addressDictionary);
            
            self.dictionary = [NSMutableDictionary dictionaryWithDictionary:self.mark.addressDictionary];
            
            NSLog(@"字典中存储的信息为:%@",self.dictionary);
            
            finishBlock(self.mark.name);
//            finishBlock(self.dictionary);
            
        });
        
    }];

}

-(NSMutableDictionary *)dictionary
{
    if (_dictionary == nil)
    {
        _dictionary = [[NSMutableDictionary alloc]init];
    }
    return _dictionary;
}


@end
